package org.flexspeedup.control
{
import flash.events.Event;

import mx.rpc.Fault;

import org.flexspeedup.event.BootCompleteEvent;
import org.flexspeedup.event.BootFaultEvent;
import org.swizframework.controller.AbstractController;
import org.swizframework.core.IInitializing;

//------------------------------------------------------------------------------
//
//  Events
//
//------------------------------------------------------------------------------
[Event(name="BootFaultEvent", type="org.flexspeedup.event.BootFaultEvent")]
[Event(name="BootCompleteEvent", type="org.flexspeedup.event.BootFaultEvent")]
/**
 * A wrapper for a regulsr <code>CommandChainController</code> that dispatches
 * boot-related events.
 */
public class BootChainController extends CommandChainController
{
    //--------------------------------------------------------------------------
    //
    // Constructor
    //
    //--------------------------------------------------------------------------
    
    /**
     * Returns a new instance of this class.
     */
    public function BootChainController()
    {
        super();
    }

    //--------------------------------------------------------------------------
    //
    //  Methods - Mediators
    //
    //--------------------------------------------------------------------------
    
    [Mediate(event="BootStartEvent.ID")]
    override public function start():void
    {
        addEventListener("chainComplete", chainCompleteHandler);
        addEventListener("chainStepError", chainErrorHandler);
        addEventListener("chainFailure", chainErrorHandler);
        super.start();
    }
 
    //--------------------------------------------------------------------------
    //
    //  Methods
    //
    //--------------------------------------------------------------------------
   
    /**
     *  @private
     */
    private function removeEventListeners():void
    {
        removeEventListener("chainComplete", chainCompleteHandler);
        removeEventListener("chainStepError", chainErrorHandler);
        removeEventListener("chainFailure", chainErrorHandler);
    }

    //--------------------------------------------------------------------------
    //
    //  Event Handlers
    //
    //-------------------------------------------------------------------------- 
       
    /**
     *  @private
     */
    private function chainCompleteHandler(event:Event):void
    {
        swizDispatcher.dispatchEvent(new BootCompleteEvent());
        removeEventListeners();
    }

    /**
     *  @private
     */   
    private function chainErrorHandler(event:Event):void
    {
        var fault:Fault = new Fault(event.type, "boot failed");
        swizDispatcher.dispatchEvent(new BootFaultEvent(fault));
        removeEventListeners();
    }    
}
}